package com.alex.tkmybatis.common.db;

import com.github.pagehelper.PageHelper;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import tk.mybatis.spring.mapper.MapperScannerConfigurer;

import javax.sql.DataSource;
import java.util.Properties;

/**
 *
 */
@Configuration
public class MapperConfig {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactoryBean(@Qualifier("dataSource") DataSource dataSource) {
        logger.info("MapperConfig.sqlSessionFactoryBean");
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        // dto所在package
        bean.setTypeAliasesPackage("com.alex.**.entity");

        // 分页插件
        PageHelper pageHelper = new PageHelper();
        Properties properties = new Properties();
        properties.setProperty("reasonable", "true");
        properties.setProperty("dialect", "mysql");
        pageHelper.setProperties(properties);
        // 添加插件
//        bean.setPlugins(new Interceptor[]{pageHelper, new CreateUpdateTimeInterceptor()});
        // 添加XML目录
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

        try {
            bean.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
        } catch (Exception e) {
        }

        try {
            return bean.getObject();
        } catch (Exception e) {
            throw new IllegalArgumentException("org.mybatis.spring.SqlSessionFactoryBean init N ", e);
        }
    }

    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        logger.info("MapperConfig.mapperScannerConfigurer");
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        // 配置多个的时候，最后一个需要以分号结尾，一个的时候是不需要分号的
        mapperScannerConfigurer.setBasePackage("com.cmft.**.mapper");
        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
        Properties properties = new Properties();
        properties.setProperty("order", "before");
        properties.setProperty("mappers", "tk.mybatis.mapper.common.Mapper");
        mapperScannerConfigurer.setProperties(properties);
        return mapperScannerConfigurer;
    }
}
